﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;

using Util.Extension;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Model.BGModels;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class RolesController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;

        public RolesController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }
        #region 角色列表
        public IActionResult Index(int menuid)
        {
            ViewBag.menuid = menuid;
            return View();
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int userType)
        {
            ListResult res = new ListResult();
            try
            {
                var data = await _context.TbRoles.Where(k => k.UserType == userType).OrderBy(k => k.Id).ToListAsync();
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data;
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        public IActionResult Checkeds(int userid, int userType)
        {
            ViewBag.userType = userType;
            ViewBag.userid = userid;
            return View();
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetUserCheckJson(int userid, int userType)
        {
            Hashtable res = new Hashtable();
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver()
            };
            try
            {
                var data = await _context.TbRoles.Where(k => k.UserType == userType).OrderBy(k => k.Id).Select(y => new
                {
                    id = y.Id,
                    names = y.Names,
                    remark = y.Remark,
                    LAY_CHECKED = _context.TbUserRoles.Where(k => k.RoleId == y.Id && k.UserId == userid && k.UserType == userType).Any()
                }).ToListAsync();
                res.Add("code", 0);
                res.Add("count", data.Count());
                res.Add("data", data);
                return new JsonResult(res, jsonSerializerSettings);
            }
            catch (Exception ex)
            {
                res.Add("code", 1);
                res.Add("msg", ex.Message);
                return new JsonResult(res, jsonSerializerSettings);
            }
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetTreeJson(int userType, string topName, int CheckedId = 0, int Id = 0)
        {
            try
            {
                if (Id != 0)
                {
                    List<RolesTreeModel> list = new List<RolesTreeModel>();
                    RolesTreeModel model = new RolesTreeModel
                    {
                        Id = 0,
                        Name = topName,
                        Open = true,
                        Checked = CheckedId == 0 ? true : false,
                        Children = _context.TbRoles.Where(k => k.UserType == userType && k.Pid == 0 && k.Id != Id).OrderBy(k => k.Id).Select(y => new
                        {
                            id = y.Id,
                            name = y.Names,
                            open = true,
                            Checked = y.Id == CheckedId ? true : false,
                            children = _context.TbRoles.Where(k => k.UserType == userType && k.Pid == y.Id && k.Id != Id).Select(n => new
                            {
                                id = n.Id,
                                name = n.Names,
                                open = true,
                                Checked = n.Id == CheckedId ? true : false
                            }).ToList()
                        }).ToList()
                    };
                    list.Add(model);
                    return new JsonResult(list);
                }
                else
                {
                    var data = _context.TbRoles.Where(k => k.UserType == userType && k.Pid == 0).OrderBy(k => k.Id).Select(y => new
                    {
                        id = y.Id,
                        name = y.Names,
                        open = true,
                        Checked = y.Id == CheckedId ? true : false,
                        children = _context.TbRoles.Where(k => k.UserType == userType && k.Pid == y.Id).Select(n => new
                        {
                            id = n.Id,
                            name = n.Names,
                            open = true,
                            Checked = n.Id == CheckedId ? true : false
                        }).ToList()
                    }).ToList();
                    return new JsonResult(data);
                }
            }
            catch (Exception)
            {
                return new JsonResult(null);
            }
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateRole(int userid, int roleid, int userType)
        {
            Result res = new Result();
            try
            {
                _context.Database.ExecuteSqlRaw($"DELETE FROM tb_user_role WHERE user_id={userid} and user_type={userType}");
                TbUserRole userRole = new TbUserRole
                {
                    RoleId = roleid,
                    UserId = userid,
                    UserType = userType
                };
                _context.TbUserRoles.Add(userRole);
                
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        public IActionResult CheckedItems(string ids, int userType)
        {
            ViewBag.userType = userType;
            ViewBag.ids = ids;
            return View();
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的角色ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("UpdateUserRolesItems")]
        public async Task<IActionResult> UpdateUserRolesItems(string ids, int roleid, int userType)
        {
            Result res = new Result();
            try
            {
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    int userId = id.ToInt();
                    if (userId == 0)
                    {
                        continue;
                    }
                    _context.Database.ExecuteSqlRaw($"DELETE FROM tb_user_role WHERE user_id={userId} and user_type={userType}");
                    TbUserRole userRole = new TbUserRole
                    {
                        RoleId = roleid,
                        UserId = userId,
                        UserType = userType
                    };
                    _context.TbUserRoles.Add(userRole);
                    
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 添加角色

        public IActionResult Create(int pid = 0, int userType = 0)
        {
            TbRole TbRole = new TbRole();
            TbRole.Pid = pid;
            if (pid == 0)
            {
                TbRole.UserType = userType;
                TbRole.Level = 1;
            }
            else
            {
                if (_context.TbRoles.Where(k => k.Id == pid && k.UserType == userType).Select(k => k.Level).FirstOrDefault() == 1)
                {
                    TbRole.UserType = userType;
                    TbRole.Level = 2;
                }
                else
                {
                    TbRole.UserType = userType;
                    TbRole.Level = 3;
                }
            }
            return View(TbRole);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Create(TbRole model)
        {
            Result res = new Result();
            try
            {
                if (!TbRoleExists(model.Names, model.UserType))
                {
                    if (_context.TbRoles.Where(k => k.Id == model.Pid).Select(m => m.Level).FirstOrDefault() == 3)
                    {
                        res.Code = 1;
                        res.Msg = "notThisAddRoles";
                    }
                    else
                    {
                        model.Creator = User.LoginName;
                        model.CreateDate = DateTimeUtil.Now;
                        
                        _context.Add(model);
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "thisRolesExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑角色信息
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            TbRole TbRole = await _context.TbRoles.FindAsync(id);
            if (TbRole == null)
            {
                return NotFound();
            }
            return View(TbRole);
        }
        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Edit(TbRole item)
        {
            Result res = new Result();
            try
            {
                if (!TbRoleExists(item.Names, item.UserType, item.Id))
                {
                    TbRole model = await _context.TbRoles.FindAsync(item.Id);
                    if (model != null)
                    {
                        if (model.Pid != item.Pid && _context.TbRoles.Where(k => k.Pid == model.Id).Any())
                        {
                            res.Code = 1;
                            res.Msg = "notUpdateThisRoles";
                            return new JsonResult(res);
                        }

                        model.Pid = item.Pid;
                        if (item.Pid == 0)
                        {
                            model.Level = 1;
                        }
                        else
                        {
                            if (_context.TbRoles.Where(k => k.Id == item.Pid).Select(k => k.Pid).FirstOrDefault() == 1)
                                model.Level = 2;
                            else
                                model.Level = 3;
                        }
                        
                        model.Names = item.Names;
                        model.Remark = item.Remark;
                        res.Code = 0;
                        
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "thisRolesExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除角色
        /// <summary>
        /// 删除单个角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("Delete")]
        public async Task<JsonResult> Delete(int id)
        {
            Result res = new Result();
            try
            {
                DelLowerRole(id);
                TbRole TbRole = await _context.TbRoles.FindAsync(id);
                
                _context.TbRoles.Remove(TbRole);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids">要删除的角色ID；多个用“,”分开</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteItems")]
        public async Task<IActionResult> DeleteItems(string ids)
        {
            Result res = new Result();
            try
            {
                List<int> list = new List<int>();
                string[] idList = ids.Split(',');
                foreach (string id in idList)
                {
                    list.Add(id.ToInt());
                }
                List<TbRole> userList = await _context.TbRoles.Where(k => list.Contains(k.Id)).ToListAsync();
                foreach (TbRole model in userList)
                {
                    _context.TbRoles.Remove(model);
                }
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        public void DelLowerRole(int id)
        {
            List<TbRole> list = _context.TbRoles.Where(k => k.Pid == id).ToList();

            foreach (TbRole role in list)
            {
                _context.TbRoles.Remove(role);
                DelLowerRole(role.Id);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Name">角色名称称</param>
        /// <param name="id">排除ID</param>
        /// <returns></returns>
        private bool TbRoleExists(string Name, int userType, int id = 0)
        {
            if (id == 0)
                return _context.TbRoles.Any(e => e.Names == Name);
            else
                return _context.TbRoles.Any(e => e.Id != id && e.Names == Name);
        }
        #endregion
    }
}